package by.gravity.common.task;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.http.client.ClientProtocolException;

import android.content.Context;
import android.os.AsyncTask;
import by.gravity.common.http.HttpClient;
import by.gravity.common.utils.StringUtil;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public abstract class CommonGsonAsyncTask<T> extends AsyncTask<String, Void, String> {

	private Context context;

	public CommonGsonAsyncTask(Context context) {
		this.context = context;
	}

	@Override
	protected String doInBackground(String... params) {
		try {
			return load(params[0]);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	private String load(String url) throws ClientProtocolException, IOException {
		if (StringUtil.isEmpty(url)) {
			return null;
		}
		return HttpClient.get(context).loadAsString(url);

	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		Type type;
		type = getType();
		if (type == null) {
			type = getTypeFromTypeArguments();
		}
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
		T resultModel = (T) gson.fromJson(result, type);
		if (resultModel != null) {
			onSuccess(resultModel);
		}

	}

	protected Type getType() {
		return null;
	}

	protected Type getTypeFromTypeArguments() {
		return (Type) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	protected abstract void onSuccess(T result);

}
